import * as module from "@/tools/util";
import * as Request from '@/api/liubike';
import store from "@/tools/factory"
import { config, isDev, defaultAreaId } from '@/api/config';

import wx  from '@/tools/wx'
import commonJs from '@/views/commonJs/common'
let that
let loginInfo = null;
const idCardReg = config.idCardReg; // 验证身份证正则


// 检测身份证号码是否为空以及是否合法
const checkIdCard = idNum => {
    if (idNum === '') {
        wx.showModal({
            title: "温馨提示",
            content: '身份证号码不能为空'
        });
        return false;
    }
    if (!idCardReg.test(idNum)) {
        wx.showModal({
            title: "温馨提示",
            content: '身份证号码错误'
        });
        return false;
    }
    return true;
}

export default {
    mixins: [commonJs],
    data() {
        return {
            item: {                 // 认证按钮
                content: "认证"
            },
            userName: '',           // 用户姓名
            idCardNum: '',          // 身份证号
            disabled: true,         // 是否允许认证
            isCorrectName: false,   // 用户名是否合法
            isCorrectId: false,      // 身份证号是否合法
            showActivity: false,
            pushCutSuccess: false,
            pushCut: false,
            money: "",
            num: "",
            phone: "",
            dialogContent: {},
            dialogContentShow: false,
            goRechargeDeposit: false  // 判断是否去充押页面
        }
    },
    mounted() {
        that = this;
        // 获取登录信息
        loginInfo = store.get('loginInfo');
        // 当前用户id
        that.setData({
            // id: options.id ? options.id : "",
            phone: loginInfo.phone
        });
        Request.getWalletV3({ areaid: store.get("childRouter").areaId || defaultAreaId }).then(res => {
            const data = res.data;
            if (data.depositStatus == "FREE") {
                that.setData({
                    goRechargeDeposit: false,
                    showActivity: true,
                });
            } else {
                if (data.hasDepositCard && data.depositCardRemains > 0) {
                    that.setData({
                        goRechargeDeposit: false
                    });
                } else {
                    if (data.deposit == 0) {
                        that.setData({
                            goRechargeDeposit: true
                        });
                    }
                }
            }
            that.setData({
                pushCut: data.pushCut,
                dialogContentShow: false
            });
        })
    },
    methods: {
        onLoad(options) {
            that = this;
            // 获取登录信息
            loginInfo = store.get('loginInfo');
            // 当前用户id
            that.setData({
                // id: options.id ? options.id : "",
                phone: loginInfo.phone
            });
            Request.getWalletV3({ areaid: store.get("childRouter").areaId || defaultAreaId }).then(res => {
                const data = res.data;
                if (data.depositStatus == "FREE") {
                    that.setData({
                        goRechargeDeposit: false,
                        showActivity: true,
                    });
                } else {
                    if (data.hasDepositCard && data.depositCardRemains > 0) {
                        that.setData({
                            goRechargeDeposit: false
                        });
                    } else {
                        if (data.deposit == 0) {
                            that.setData({
                                goRechargeDeposit: true
                            });
                        }
                    }
                }
                that.setData({
                    pushCut: data.pushCut,
                    dialogContentShow: false
                });
            })
        },
        onShow() {
            // that.getRegistration()
        },
        closePushCutSuccess() {
            that.setData({
                pushCutSuccess: false
            });
            let p = getCurrentPages().length;
            wx.navigateBack({ delta: 1 });
        },
        getUserName(ev) { // 获取用户名
            const curDetail = ev.target;
            const curValue = curDetail.value.trim();
            that.setData({
                isCorrectName: curValue === '' ? false : true,
                userName: curValue
            });
            // 检测所有用户名和身份证输入是否合法
            that.isAllCorrect();
        },
        getIdCardNum(ev) { // 获取身份证号码
            const curDetail = ev.target;
            const curValue = curDetail.value;
            that.setData({
                isCorrectId: idCardReg.test(curValue) ? true : false,
                idCardNum: curDetail.value
            });

            that.isAllCorrect();
        },
        authOpts() { // 认证
            const APPDATA = that._data;
            if (APPDATA.userName === '') {
                wx.showModal({
                    title: "温馨提示",
                    content: '姓名不能为空',
                    showCancel: false
                });
                return;
            };
            // 检测身份证是否合法
            if (!checkIdCard(APPDATA.idCardNum)) return;
            // 判断当前身份证是否存在
            that.isExist();
        },
        isExist() { // 判断当前身份证是否存在 GET
            const APPDATA = that._data;
            wx.showLoading({
                title: "身份认证中..."
            });
            // 认证请求
            Request.authFn({
                identity: APPDATA.idCardNum,
                fillname: APPDATA.userName
            }).then(res => {
                const req = module.isArray(res) ? res[0] : res;
                // 隐藏Loading
                wx.hideLoading();

                if (req.success) {
                    if (APPDATA.pushCut) {
                        Request.checkCut().then(res => {
                            if (res.success) {
                                that.setData({
                                    money: res.data.money,
                                    num: res.data.remains,
                                    pushCutSuccess: true
                                })
                            } else {
                                wx.showToast({
                                    title: res.msg,
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        })
                    } else {
                        wx.showModal({
                            title: "温馨提示",
                            content: '认证成功',
                            showCancel: false,
                            success() {
                                // wx.navigateBack({ delta: 1 });
                                that.getRegistration()
                            }
                        });
                    }
                    // 存储实名认证成功状态
                    store.set('isAuth', 'auth');
                } else {
                    if (req.code == "20103011") {
                        wx.showModal({
                            title: "认证失败",
                            content: req.message,
                            cancelText: "重新认证", //默认是“取消”
                            confirmText: "更换号码", //默认是“确定”
                            success(res) {
                                console.log(res, 'res')
                                // gwsign  zkl
                                module.removeStorages(["loginInfo", 'gwsSalt'])
                                wx.redirectTo({
                                    url: '/mobileLogin'
                                });
                            },
                            fail(res) {
                                console.log(res, 'resksksksksk')
                            }
                        });
                    } else {
                        wx.showModal({
                            title: "认证失败",
                            content: req.message,
                            showCancel: false,
                            success() { }
                        });
                    }
                }
            }).catch(err => {
                // 认证失败后关闭loading, 并提示认证失败原因
                wx.hideLoading();
                wx.showModal({
                    title: "温馨提示",
                    content: err.data.message,
                    showCancel: false,
                    success() {
                        if (loginInfo) {
                            let p = getCurrentPages().length;
                            wx.navigateBack({ delta: p - 1 });
                        } else {
                            wx.redirectTo({
                                url: '/autoLogin'
                            });
                        }
                    }
                });
            });
        },
        tel: function () {
            that.pointReport('view_contactTel', {}, that)
            wx.makePhoneCall({
                phoneNumber: '4006076666',
            })
        },
        getRegistration() {
            Request.getRegistration().then(res => {
                if (res.success) {
                    that.setData({
                        dialogContent: res.data,
                        dialogContentShow: true
                    })
                } else {
                    wx.navigateBack({ delta: 1 });
                }
            }).catch(err => {
                wx.navigateBack({ delta: 1 });
            })
        },
        closeDialog() {
            wx.navigateBack({ delta: 1 });
        },
        cardClick() {
            let linkUrl = that._data.dialogContent.linkUrl;
            if (linkUrl.indexOf("https") != -1) {
                if (linkUrl.indexOf("needAreaId") != -1) {
                    const locationInfo = store.get("initLocationInfo");
                    store.set("wxWeb", `${linkUrl}&token=${store.get("loginInfo").token}&areaId=${store.get('childRouter').areaId}&lat=${locationInfo.lat}&lng=${locationInfo.lng}`);
                    wx.redirectTo({
                        url: `/wxWeb`
                    });
                    return false
                }
                if (linkUrl.indexOf("needlogin") != -1) {
                    store.set("wxWeb", `${linkUrl}&token=${store.get("loginInfo").token}`)
                    wx.redirectTo({
                        url: `/wxWeb`
                    });
                } else {
                    store.set("wxWeb", `${linkUrl}`)
                    wx.redirectTo({
                        url: `/wxWeb`
                    });
                }
            } else {
                wx.redirectTo({
                    url: linkUrl
                })
            }
        },
        createAuth() { // 未认证创建认证
            const APPDATA = that._data;
            const formatType = 'YYYY-MM-DD hh:mm:ss'; // 格式化日期格式
            wx.showLoading({
                title: "身份认证中..."
            });

            Request.authFn({
                identity: APPDATA.idCardNum,
                fillname: APPDATA.userName
            }).then(res => {
                const req = module.isArray(res) ? res[0] : res;
                const data = req.data;
                const CURR_IDNUM = data.identity;
                const fillname = APPDATA.userName,
                    identity = APPDATA.idCardNum;
                Request.updateAuthInfo({
                    fillname,
                    identity
                }).then(res => {
                    // 认证成功后关闭loading
                    wx.hideLoading();
                    if (res.success) {
                        // 存储实名认证成功状态
                        store.set('isAuth', 'auth');
                        wx.showModal({
                            title: "认证成功",
                            content: '您可以开始用车啦',
                            showCancel: false,
                            success() {
                                let p = getCurrentPages().length;
                                wx.navigateBack({ delta: 1 });
                            }
                        });
                    } else {
                        wx.showModal({
                            title: "认证失败",
                            content: res.message,
                            showCancel: false,
                            success() { }
                        });
                    }

                }).catch(err => {
                    // 认证失败后关闭loading, 并提示认证失败原因
                    wx.hideLoading();
                    wx.showModal({
                        title: "认证失败",
                        content: err.data.message,
                        showCancel: false,
                        success() {
                            if (CURR_IDNUM) { // 已有实名认证信息
                                // 存储实名认证成功状态
                                store.set('isAuth', 'auth');
                                if (loginInfo) {
                                    if (APPDATA.goRechargeDeposit) {
                                        wx.redirectTo({
                                            url: '/rechargeDeposit'
                                        });
                                    } else {
                                        let p = getCurrentPages().length;
                                        wx.navigateBack({ delta: 1 });
                                    }
                                } else {
                                    wx.redirectTo({
                                        url: '/autoLogin'
                                    });
                                }
                            }
                        }
                    });
                });
            });
        },
        isAllCorrect() { // 验证姓名、身份证号是否正确
            const APPDATA = that._data;
            if (APPDATA.isCorrectName && (APPDATA.idCardNum.length == 15 || APPDATA.idCardNum.length == 18)) {
                that.setData({
                    disabled: false
                });
                return;
            }
            that.setData({
                disabled: true
            });
        },
    }
}
